import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/api';

@Component({
    templateUrl: './media-upload.component.html',
    styleUrls: ['./media-upload.component.scss']
})
export class MediaUploadComponent implements OnInit {
    catalogs: any = [];
    selectedCatalog: any;
    uploadedFiles: any[] = [];
    data: any;
    systemUrl: string;
    constructor(
        private http: HttpClient,
        private ref: DynamicDialogRef,
        private config: DynamicDialogConfig) {
        this.data = this.config.data.rowData || {};
        this.systemUrl = this.config.data.systemUrl;
    }

    ngOnInit() {
        this.http.get("/" + this.systemUrl + "/api/tab/media/catalog").subscribe(data => {
            this.catalogs = data['data'];
            this.selectedCatalog = this.catalogs[0].value;
        });
    }

    onFileUploadHandler(event, file) {
        let groupName = '';
        this.catalogs.forEach(ele => {
            if (ele.value == this.selectedCatalog) {
                groupName = ele.label;
                return;
            }
        });
        const formData: FormData = new FormData();
        let files = event.files;
        for (let i = 0; i < files.length; i++) {
            formData.append('files', event.files[i], event.files[i].name);
        }
        formData.append('relationId', this.data.recId || this.data.rec_is || "");
        formData.append('actDefId', this.data.actDefId || this.data.act_def_id || "");
        formData.append('actDefName', this.data.actDefName || this.data.act_def_name || "");
        formData.append('bizId', this.data.bizId || this.data.biz_id || "");
        formData.append('groupId', this.selectedCatalog);
        formData.append('groupName', groupName);
        this.http.post('/' + this.systemUrl + '/api/tab/media/upload', formData).subscribe(data => {
            this.ref.close(data);
        })
        file.clear();
    }
}